#pragma once

// 网络四件套，很网络相关一定要这四个库
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
// 其他库函数
#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <cstring>
#include <string>
#include <cerrno>
#include <cassert>
#include <cstdlib>
#include<thread>
#include<pthread.h>
using namespace std;
// namespace std;
void service(int& sock,string& ip,uint16_t& port)
{
    char buffer[1024] = {0};
    while(true)
    {
        ssize_t s=read(sock,buffer,sizeof(buffer)-1);
        if(s>0)
        {
            buffer[s]=0;
            cout<<ip<<":"<<port<<"# "<<buffer<<endl;

        }
        else if(s==0)
        {
            cout<<"#正常关闭终端#"<<endl;
            break;
        }
        else
        {
            cout<<"error,wo will shut down"<<endl;
            break;
        }

        write(sock,buffer,strlen(buffer));
    }
}

class TCPSocket
{
public:
    const static int gbacklog=20;
    TCPSocket(uint16_t port, std::string ip = "0.0.0.0")
        : _port(port),
          _ip(ip),
          _sock(-1)
    {
    }
    void Initiate()
    {
        // 创建套接字
        _sock = socket(AF_INET, SOCK_STREAM, 0);//SOCK_DGRAM->SOCK_STREAM
        if (_sock < 0)
        {
            std::cerr << errno << ":" << strerror(errno) << endl;
            exit(2);
        }
        cout<<"sock:"<<_sock<<endl;
        // bind绑定套接字
        struct sockaddr_in local;
        //bzero(&local, sizeof(local)); // 把结构体清零
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr =   inet_addr(_ip.c_str()); // 一步到位将点十进制字符串峰哥的IP地址->4字节->网络序列化
        if (bind(_sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            std::cerr << errno << "bind error:" << strerror(errno) << endl;
            exit(3);
        }

        //连接
        if(listen(_sock,gbacklog)<0)
        {
            std::cerr << errno << "listen error:" << strerror(errno) << endl;
            exit(4);
        }
        cout << "init TCP server done... " << strerror(errno) << endl;
    }

    void Start()
    {
        // 网络服务器永远不会退出的->常驻进程->永远存在的，除非挂了！
        // echo
        while(true)
        {
            socklen_t len = sizeof(struct sockaddr);
            struct sockaddr_in in;
            //bzero(&peer,sizeof(peer));//必须初始化
            // 读取数据
            //ssize_t read_size = recvfrom(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            int SvrSock=accept(_sock,(sockaddr*)&in,&len);//tcp 用的不再是recvfrom，而是accept
            if (SvrSock < 0)
            {
                perror("accept");
                continue;
            }

            uint16_t clt_port = ntohs(in.sin_port);
            string clt_ip = inet_ntoa(in.sin_addr);
            printf("[%s,%d] # \n",clt_ip.c_str(),clt_port);

            // 分析處理數據  ctrl+Z是后台运行,不是退出,要用+C
            pid_t id=fork();
            assert(id!=-1);
            if(id==0)
            {
                //子进程用不到sock了直接关掉就好
                close(_sock);
                service(SvrSock,clt_ip,clt_port);
                exit(0);//僵尸状态
            }
            //sendto(_sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, len);
            close(SvrSock);
        }
    }

    ~TCPSocket()
    {
        if (_sock >= 0)
            close(_sock);
    }

private:
    int _sock;
    uint16_t _port;
    string _ip;
};

